<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;

use api\common\controller\ApiBaseController;
use api\portal\model\MerchModel;
use app\admin\model\NavMenuModel;
use model\GoodsModel;
use think\db\Query;
use think\facade\Db;

class IndexController extends ApiBaseController
{

    /**
     * 获取网站信息
     */
    public function config()
    {
        $data = cmf_get_option('site_info');
        $this->success('请求成功!', $data);
    }

    /**
     * 首页
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        //轮播
        $slider = Db::name('slide_item')->where('status', 1)->field('title,image,url')->select()->toArray();
        foreach ($slider as &$item) {
            $item['image'] = cmf_get_image_url($item['image']);
        }

        //分类
        $category = Db::name('nav_menu')
            ->alias('nm')
            ->leftJoin('nav n', 'n.id = nm.nav_id')
            ->where('n.is_main', 1)
            ->field('nm.id,nm.name,nm.href,nm.api,nm.icon,nm.url')
            ->select()->toArray();

        //活动
        $activity = Db::name('nav_menu')
            ->alias('nm')
            ->leftJoin('nav n', 'n.id = nm.nav_id')
            ->where('n.is_main', 0)
            ->field('nm.name,nm.href,nm.api,nm.icon,nm.lantype,n.is_main as ptype, nm.url')
            ->select()->toArray();

        $result = [
            'banner' => $slider,
            'category' => $category,
            'activity' => $activity,
        ];

        $this->success('请求成功', $result);
    }

    /**
     * 商品列表
     */
    public function goodsList()
    {

        $param = $this->request->post();

        $order = empty($param['order']) ? 'id' : $param['order'];
        $name = empty($param['name']) ? '' : $param['name'];
        $sort = empty($param['sort']) ? 'desc' : $param['order'];
        $page = isset($param['page']) ? $param['page'] : 0;
        $limit = empty($param['limit']) ? 10 : $param['limit'];

        if ($page <= 1) {
            $offset = 0;
        } else {
            $offset = $limit * ($page - 1);
        }

        $goodsList = Db::name('goods')->where('is_delete', 0)
            ->field('category_id,id,title,thumb,stock,under_price,price,sales_num,sort,thumb,check,status,merch_id,hot,sale,recomment')
            ->where(function (Query $query) use ($param, $name) {
                if (!empty($name)) {
                    $query->where('title', 'like', "%$name%");
                }
                if (!empty($param['is_hot'])) {
                    $query->where('hot', 1);
                }
                if (!empty($param['is_sale'])) {
                    $query->where('sale', 1);
                }
                if (!empty($param['is_recomment'])) {
                    $query->where('recomment', 1);
                }
                if (!empty($param['category_id'])) {
                    $query->where('category_id', $param['category_id']);
                }
            })->limit($offset, $limit)->order($order, $sort)->select()->toArray();
        foreach ($goodsList as $key => &$item) {
            $item = GoodsModel::decode($item);
        }
        return $this->success('获取成功', $goodsList);
    }

    /**
     * 热卖
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getHotGoods()
    {
        //热卖
        $data = Db::name('goods')
            ->where([
                'status' => 1,
                'hot' => 1,
                'check' => 1,
            ])
            ->where('stock', '>', 0)
            ->order('sort', 'DESC')
            ->field('id,title,thumb,stock,under_price,price,sales_num,sort')
            ->limit(5)
            ->select()->toArray();

        foreach ($data as &$value) {
            $value['thumb'] = cmf_get_asset_url($value['thumb']);
        }

        $this->success('请求成功', $data);
    }

    /**
     * 推荐
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRecomment()
    {

        //推荐
        $data = Db::name('goods')
            ->where([
                'status' => 1,
                'recomment' => 1,
                'check' => 1,
            ])
            ->where('stock', '>', 0)
            ->order('sort', 'DESC')
            ->field('id,title,thumb,stock,under_price,price,sales_num,sort')
            ->limit(5)
            ->select()->toArray();

        foreach ($data as &$value) {
            $value['thumb'] = cmf_get_asset_url($value['thumb']);
        }

        $this->success('请求成功', $data);
    }

    /**
     * 获取数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMerchList()
    {
        $lat = $this->request->get('lat', 0);
        $lng = $this->request->get('lng', 0);

        $page = isset($param['page']) ? $param['page'] : 0;
        $limit = empty($param['limit']) ? 10 : $param['limit'];

        if ($page <= 1) {
            $offset = 0;
        } else {
            $offset = $limit * ($page - 1);
        }

        $select = ['id', 'title', 'category'];
        $select[] = "(6371 * acos ( cos ( \
        radians( {$lat} ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( {$lng} ) ) + sin ( radians( {$lat} ) ) * sin( radians( lat ) ) ) ) AS distance";
        $merch = MerchModel::where(['status' => 1, 'city_id' => $this->userCity])->field($select)->limit($offset, $limit)->order('distance asc')->limit(20)->select()->toArray();
        foreach ($merch as &$item) {
            $item['category_name'] = NavMenuModel::where(['id' => $item['category']])->field('*')->find()['name'];
            if (empty($lat) || empty($lng)) {
                $item['distance'] = 0;
            }
        }

        $this->success('请求成功', $merch); 
    }


    /**
     * 促销
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSale()
    {
        //促销
        $data = Db::name('goods')
            ->where([
                'status' => 1,
                'sale' => 1,
                'check' => 1,
            ])
            ->where('stock', '>', 0)
            ->order('sort', 'DESC')
            ->field('id,title,thumb,stock,under_price,price,sales_num,sort')
            ->limit(5)
            ->select()->toArray();


        foreach ($data as &$value) {
            $value['thumb'] = cmf_get_asset_url($value['thumb']);
        }
        $this->success('请求成功', $data);
    }

    /**
     * 获取小程序图
     */
    public function getQrcode()
    {

        $page = $this->request->post('page');
        $params = $this->request->post('params');
        $scene = '';


//        if (empty($page) || empty($params)) {
//            return $this->error('数据错误');
//        }
//
//        foreach ($params as $key => $value) {
//            $scene .= $key . '_' . $value . ':';
//        }
//        $scene = rtrim(':', $scene);

        $accessToken = $this->getAccessToken();
        $res = MerchModel::getQrcode($accessToken, $page, $params);
        return $this->success('请求成功', ['url' => $res]);
    }


}
